package com.alex.alexelasticsearch.service;

import com.alex.alexelasticsearch.model.Alex008Product;
import com.alex.alexelasticsearch.repository.Alex008ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 商品搜索服务类 - 简化版本，避免复杂的原生查询
 */
@Service
public class Alex008ProductSearchService {

    @Autowired
    private Alex008ProductRepository productRepository;

    @Autowired
    private ElasticsearchOperations elasticsearchOperations;

    /**
     * 初始化测试数据
     */
    public void initTestData() {
        // 删除整个索引，重新创建
        try {
            elasticsearchOperations.indexOps(Alex008Product.class).delete();
            elasticsearchOperations.indexOps(Alex008Product.class).create();
            elasticsearchOperations.indexOps(Alex008Product.class).putMapping();
        } catch (Exception e) {
            System.out.println("索引操作异常，继续执行...");
        }

        // 清空现有数据
        productRepository.deleteAll();

        // 创建测试商品数据
        List<Alex008Product> products = List.of(
            new Alex008Product("iPhone 15 Pro Max 256GB", "苹果最新旗舰手机，A17 Pro芯片，钛金属设计", 
                              "Apple", "手机", new BigDecimal("9999.00"), 15000L, 4.8, 500L, "5G", "拍照", "游戏"),
            new Alex008Product("华为 Mate 60 Pro", "华为回归之作，麒麟9000S芯片，卫星通话", 
                              "Huawei", "手机", new BigDecimal("6999.00"), 25000L, 4.7, 800L, "5G", "商务", "拍照"),
            new Alex008Product("小米14 Ultra", "小米影像旗舰，徕卡镜头，骁龙8 Gen3", 
                              "Xiaomi", "手机", new BigDecimal("5999.00"), 18000L, 4.6, 1200L, "5G", "拍照", "性价比"),
            new Alex008Product("MacBook Pro 14英寸 M3", "苹果笔记本电脑，M3芯片，14英寸Liquid Retina XDR显示屏", 
                              "Apple", "笔记本", new BigDecimal("14999.00"), 8000L, 4.9, 200L, "办公", "设计", "编程"),
            new Alex008Product("联想ThinkPad X1 Carbon", "商务笔记本，轻薄便携，第11代Intel处理器", 
                              "Lenovo", "笔记本", new BigDecimal("12999.00"), 6000L, 4.5, 300L, "商务", "办公", "轻薄"),
            new Alex008Product("戴尔XPS 13", "超极本，无边框设计，第12代Intel处理器", 
                              "Dell", "笔记本", new BigDecimal("8999.00"), 4500L, 4.4, 150L, "轻薄", "学生", "办公"),
            new Alex008Product("AirPods Pro 2", "苹果无线耳机，主动降噪，空间音频", 
                              "Apple", "耳机", new BigDecimal("1999.00"), 50000L, 4.7, 2000L, "降噪", "无线", "音质"),
            new Alex008Product("索尼WH-1000XM5", "头戴式降噪耳机，30小时续航，Hi-Res音质", 
                              "Sony", "耳机", new BigDecimal("2399.00"), 12000L, 4.8, 800L, "降噪", "HiFi", "长续航")
        );
        
        // 批量保存到 ES
        productRepository.saveAll(products);
        System.out.println("初始化了 " + products.size() + " 个商品数据");
    }

    /**
     * 简单关键词搜索
     */
    public List<Alex008Product> simpleSearch(String keyword) {
        return productRepository.searchByKeyword(keyword);
    }

    /**
     * 高级搜索 - 使用 Spring Data ES 的方法查询，避免复杂的原生查询
     */
    public Page<Alex008Product> advancedSearch(String keyword, String category, String brand,
                                               BigDecimal minPrice, BigDecimal maxPrice,
                                               String sortBy, String sortOrder,
                                               int page, int size) {
        
        // 创建分页和排序
        Sort sort = Sort.unsorted();
        if (sortBy != null && !sortBy.trim().isEmpty()) {
            Sort.Direction direction = "desc".equalsIgnoreCase(sortOrder) ? 
                Sort.Direction.DESC : Sort.Direction.ASC;
            sort = Sort.by(direction, sortBy);
        }
        
        Pageable pageable = PageRequest.of(page, size, sort);
        
        // 使用 Repository 的方法查询，避免复杂的 BoolQuery
        if (keyword != null && !keyword.trim().isEmpty() && category != null && !category.trim().isEmpty()) {
            // 关键词 + 分类 + 价格区间
            if (minPrice != null && maxPrice != null) {
                return productRepository.findByProductNameContainingAndCategoryAndPriceBetween(
                    keyword, category, minPrice, maxPrice, pageable);
            }
            // 仅关键词 + 分类
            return (Page<Alex008Product>) productRepository.findByProductNameContaining(keyword)
                    .stream()
                    .filter(p -> p.getCategory().equals(category))
                    .collect(Collectors.toList())
                    .stream()
                    .skip(page * size)
                    .limit(size)
                    .collect(Collectors.toList())
                    .stream()
                    .collect(Collectors.toList());
        }
        
        // 仅关键词搜索
        if (keyword != null && !keyword.trim().isEmpty()) {
            List<Alex008Product> results = productRepository.findByProductNameContaining(keyword);
            // 简单分页处理
            int start = page * size;
            int end = Math.min(start + size, results.size());
            List<Alex008Product> pageContent = results.subList(start, end);
            return new PageImpl<>(pageContent, pageable, results.size());
        }
        
        // 仅分类筛选
        if (category != null && !category.trim().isEmpty()) {
            List<Alex008Product> results = productRepository.findByCategory(category);
            return new PageImpl<>(results, pageable, results.size());
        }
        
        // 仅品牌筛选
        if (brand != null && !brand.trim().isEmpty()) {
            List<Alex008Product> results = productRepository.findByBrand(brand);
            return new PageImpl<>(results, pageable, results.size());
        }
        
        // 仅价格区间
        if (minPrice != null && maxPrice != null) {
            List<Alex008Product> results = productRepository.findByPriceBetween(minPrice, maxPrice);
            return new PageImpl<>(results, pageable, results.size());
        }
        
        // 默认返回所有数据
        return productRepository.findAll(pageable);
    }

    /**
     * 搜索并高亮显示 - 简化版本
     */
    public List<Map<String, Object>> searchWithHighlight(String keyword) {
        List<Alex008Product> products = productRepository.searchByKeyword(keyword);
        
        return products.stream().map(product -> {
            // 简单的高亮处理，实际项目中使用原生查询
            String highlightedName = product.getProductName().replaceAll(
                "(?i)" + keyword, "<em style='color:red'>" + keyword + "</em>");
            String highlightedDesc = product.getDescription().replaceAll(
                "(?i)" + keyword, "<em style='color:red'>" + keyword + "</em>");
            
            return Map.of(
                "product", product,
                "highlights", Map.of(
                    "productName", List.of(highlightedName),
                    "description", List.of(highlightedDesc)
                ),
                "score", 1.0  // 简化的得分
            );
        }).collect(Collectors.toList());
    }

    /**
     * 获取搜索建议 - 简化版本
     */
    public List<String> getSearchSuggestions(String prefix) {
        if (prefix == null || prefix.trim().length() < 2) {
            return List.of();
        }
        
        // 使用包含查询作为建议
        List<Alex008Product> products = productRepository.findByProductNameContaining(prefix);
        
        return products.stream()
                .map(Alex008Product::getProductName)
                .distinct()
                .limit(10)
                .collect(Collectors.toList());
    }

    /**
     * 获取聚合统计信息
     */
    public Map<String, Object> getAggregationStats() {
        long totalProducts = productRepository.count();
        
        return Map.of(
            "totalProducts", totalProducts,
            "message", "简化版统计信息"
        );
    }
}